---
import type { GetStaticPaths } from 'astro'
import PageLayout from '@/layouts/PageLayout.astro'
import PostList from '@/components/post/PostList.astro'
import PostPagination from '@/components/post/PostPagination.astro'
import { getSortedPosts, getHotTags, getAllCategories, getAllTags } from '@/utils/content'
import appConfig from '@/config.json'
import SectionBlock from '@/components/SectionBlock.astro'
import TagList from '@/components/TagList.astro'
import CategoryList from '@/components/CategoryList.astro'
import type { CollectionEntry } from 'astro:content'
import Hero from '@/components/hero/Hero.astro'

export const getStaticPaths = (async () => {
  const sortedPosts = await getSortedPosts()
  const { perPage } = appConfig.posts
  const totalPage = Math.ceil(sortedPosts.length / perPage)

  const paths = Array.from({ length: totalPage }).map((_, i) => {
    const data = sortedPosts.slice(i * perPage, (i + 1) * perPage)
    const props = { currentPage: i + 1, totalPage, data }
    const params = {
      page: i === 0 ? undefined : `page/${i + 1}`,
    }
    return { params, props }
  })

  return paths
}) satisfies GetStaticPaths

interface Props {
  currentPage: number
  totalPage: number
  data: CollectionEntry<'posts'>[]
}

const { currentPage, totalPage, data } = Astro.props

const hotTags = await getHotTags()
const allTags = await getAllTags()
const allCategories = await getAllCategories()

const getPageUrl = (page: number) => {
  if (page === 1) return '/'
  return `/page/${page}`
}
---

<PageLayout>
  <div>
    {currentPage === 1 && <Hero />}
    <div class="max-w-[1100px] px-4 md:px-8 py-20 mx-auto grid lg:grid-cols-[auto_300px] gap-10">
      <div class="min-w-0">
        <SectionBlock title="最新发布">
          <PostList posts={data} />
          {
            totalPage > 1 && (
              <PostPagination current={currentPage} total={totalPage} getPageUrl={getPageUrl} />
            )
          }
        </SectionBlock>
      </div>
      <div>
        <aside class="md:sticky md:top-20 space-y-10">
          <SectionBlock title="分类">
            <CategoryList categories={allCategories} />
          </SectionBlock>
          <SectionBlock title="热门标签">
            <TagList tags={hotTags} />
            {
              allTags.length > hotTags.length && (
                <div class="mt-2 text-right">
                  <a class="text-sm text-secondary hover:text-accent" href="/tags">
                    更多标签 <i class="iconfont icon-arrow-right" />
                  </a>
                </div>
              )
            }
          </SectionBlock>
        </aside>
      </div>
    </div>
  </div>
</PageLayout>
